﻿// this file handles all application db requests
var Database = {
    initialized: false,
    db : null,
    shortName: "db_webapp",
    version: "1.0",
    displayName: "WebApp",
    maxSize: 65536,
    isInitialized: function () {
        return this.initialized;
    },
    createDB: function() {
        // creates DB
        try {
            if (window.openDatabase) {
                db = openDatabase(this.shortName, this.version, this.displayName, this.maxSize);
                this.initialized = true;
            }
        } catch (e) {
            alert(e);
        }
    },
    open: function() {
        return openDatabase(this.shortName, this.version, this.displayName, this.maxSize);
    },
    init: function () {
        // init DB
    	if (!Database.isInitialized()) {
    		Database.createDB();
    	}
    },
    insert: function (table, jsonObject, callback, errorCallback, command) {
        // insert an object to DB - table columns and object members must match!
        var sqlCommand = command || "insert";
    	var sqlStatement = sqlCommand + " into " + table + " ";
        var columns = "";
        var valuesString = "";
        var values = [];

        if (!callback) {
            callback = Database.onNull;
        }
        if (!errorCallback) {
            errorCallback = Database.onError;
        }

        for (var key in jsonObject) {
        	if (jsonObject.hasOwnProperty(key)) {
	            if (columns)
	                columns += ", ";
	            columns += key;
	
	            values.push(jsonObject[key]);
	            if (valuesString)
	                valuesString += ", ";
	            valuesString += "?";
        	}
        }
        columns = "(" + columns + ")";
        valuesString = "(" + valuesString + ")";


        sqlStatement += columns + " values " + valuesString + ";";
        try {
            db.transaction(
                function (transaction) {
                    transaction.executeSql(sqlStatement, values, callback, errorCallback);
                }
            );
            return true;
        } catch (e) {
            alert(e);
            return false;
        }
    },
    insertOrUpdate: function(table, jsonObject, callback, errorCallback) {
    	Database.insert(table, jsonObject, callback, errorCallback, "insert or replace");
    },
    update: function (table, jsonObject, callback, errorCallback) {
        // updates an object to DB - table columns and object members must match!
        var sqlStatement = "update " + table + " set ";
        var columns = "";
        var values = [];

        if (!callback) {
            callback = Database.onNull;
        }
        if (!errorCallback) {
            errorCallback = Database.onError;
        }

        for (var key in jsonObject) {
            if (columns)
                columns += ", ";
            columns += key + "=?";

            values.push(jsonObject[key]);
        }

        sqlStatement += columns + " where id=?";
        values.push(jsonObject.id); // item id is the filter
        try {
            db.transaction(
                function (transaction) {
                    transaction.executeSql(sqlStatement, values, callback, errorCallback);
                }
            );
            return true;
        } catch (e) {
            alert(e);
            return false;
        }
    },
    get: function (table, filter, callback) {
        // get a table based on a filter
        var sqlStatement = "select * from " + table;
        if (filter) {
            sqlStatement += " where " + filter;
        }
        try {
            db.transaction(
                function (transaction) {
                    transaction.executeSql(sqlStatement, [], callback, Database.onError);
                }
            );
        } catch (e) {
            alert(e);
            return false;
        }
    },
    onData: function(transaction, results)
    {
        var retValues = new Array();
        // Handle the results
        var newItem;

        for (var i = 0; i < results.rows.length; i++) {
            newItem = {};
            var row = results.rows.item(i);

            for (var key in row) {
                newItem[key] = row[key];
            }

            retValues.push(newItem);
        }
        
        return retValues;
    },
    onNull: function (tx, results) {
    },
    onError: function(tx, error) {
        alert(error.message);
        console.log(error);
    },
    executeSql: function (sqlStatement, options, callback, errorCallback) {
        // executes an sql statement
        if (!callback) // if null
            callback = Database.onData;
        if (!errorCallback) // if null
            errorCallback = Database.onError;

        db.transaction(
                function (transaction) {
                    transaction.executeSql(sqlStatement, options, callback, errorCallback);
                }
            );
    }
};

Database.init();